package logging;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Logfile
 * 
 * @author norrielm
 *
 */
public class LogToFile {

	public String name;
	private FileOutputStream fo = null;
	private String path;

	/**Initialise with chosen filename*/
	public LogToFile(String filename){
		name = filename;
		create();
	}

	/**Create the file to write in to, save on the phone's sdcard*/
	public void create(){
		try {			
			path =  name +".txt";

			System.out.println( "creating file " + path);
			// make sure the directory we plan to store the recording in exists
			/*File directory = new File(path).getParentFile();
			if (!directory.exists() && !directory.mkdirs()) {
				System.out.println( "log dir not found");			
			}*/



			File file = new File(path);
			fo=new FileOutputStream(file, true);

		} catch (FileNotFoundException e) {
			System.out.println("Could not open log file " + e);
		}catch(Exception e){
			System.out.println( "Could not open log file " + e);
		}
	}

	/**Write a string*/
	public void write(String s){
		if(fo!= null){
			try {
				s+="\n";
				fo.write(s.getBytes());
			} catch (IOException e) {

			}
		}else{

		}
	}

	/**Write a string with the time beside it [hh:mm]*/
	public void writeWTime(String s){
		if(fo!= null){
			try {
				String time = System.currentTimeMillis() +" ";//DateFormat.format("hh:mm:ss", new Date()) + ")"; 
				time += s+"\n"; 
				fo.write(time.getBytes());
			} catch (IOException e) {

			}
		}else{

		}
	}	
	
	/**Returns the path to the log*/
	public String getFilename(){
		return path;
	}

	/**Close the log file*/
	public void close(){
		if(fo!=null){
			try {
				fo.close();
			} catch (IOException e) {
				//	Log.d("logfile" , "could not close fo " + e);				
			}
		}
	}

}


